package cn.com.generaldata.os.service.indicator_evaluation.sustainable_development;

import org.nutz.dao.sql.Criteria;

import cn.com.generaldata.jsme_indicator_system.entity.IndicatorEvaluation;
import cn.com.generaldata.jsme_indicator_system.util.Constants;
import cn.com.generaldata.os.service.indicator_constant.ProvinceIndicatorConstant;
import cn.com.generaldata.os.service.indicator_evaluation.IndicatorEvaluationCalculateService;
import cn.com.generaldata.os.vo.IndicatorAccountVO;

/**
 * 可持续发展引用相关输入指标标准化计算类.
 */
public class IndicatorInputStandardCalculateService extends IndicatorEvaluationCalculateService {

	private int baseYear = ProvinceIndicatorConstant.PROVINCE_DATA_START_YEAR;

	@Override
	protected Double calculate(IndicatorEvaluation indicator, IndicatorAccountVO indicatorAccountVO) {
		Double result = null;
		if (indicator.getSection() == Constants.INDICATOR_LEVEL_PROVINCE) {
			result = calculateProvinceResult(indicator, indicatorAccountVO);
		} else if (indicator.getSection() == Constants.INDICATOR_LEVEL_CITY) {
			// 市指标没确定先保留
		}
		return result;
	}

	/**
	 * 计算江苏省进出口总额增长率评估指标计算类.
	 * 
	 * @param indicator
	 * @param indicatorAccountVO
	 * @return
	 */
	private Double calculateProvinceResult(IndicatorEvaluation indicator, IndicatorAccountVO indicatorAccountVO) {
		Double indicatorVal = getIndicatorVal(indicatorAccountVO, indicatorAccountVO.getYear(), indicator);

		Double avgIndicatorVal = getAvgIndicatorVal(indicatorAccountVO, indicator);

		return Double.valueOf(0).equals(avgIndicatorVal) ? 0d : indicatorVal / avgIndicatorVal;
	}

	private Double getIndicatorVal(IndicatorAccountVO indicatorAccountVO, int year, IndicatorEvaluation indicator) {

		Integer indicatorId = getIndicatorInputId(indicator.getReference(), null);
		Criteria cri = getIndicatorDataCri(indicatorAccountVO, year, indicatorId);
		Double result = getInputIndicatorValue(cri);

		return result == null ? 0d : result;
	}

	/**
	 * 获得指标的均值.
	 * 
	 * @param indicatorAccountVO
	 * @param indicator
	 * @return
	 */
	private Double getAvgIndicatorVal(IndicatorAccountVO indicatorAccountVO, IndicatorEvaluation indicator) {
		Double indicatorValSum = 0d;
		int haveDataYears = 0;
		int maxYear = getInputOrAccountingMaxYear(indicator.getReference(), indicatorAccountVO.getAreaId());
		for (int year = baseYear; year <= maxYear; year++) {
			Double indicatorVal = getIndicatorVal(indicatorAccountVO, year, indicator);
			if (!Double.valueOf(0).equals(indicatorVal)) {
				indicatorValSum += indicatorVal;
				haveDataYears++;
			}
		}
		return haveDataYears == 0 ? 0d : indicatorValSum / haveDataYears;
	}

}
